$(function () {
    //初始化函数
    function  init() {
        //图片上传功能
        let fileDom = document.querySelector('#inputCover')
        fileDom.onchange = function () {
            let file = this.files[0]
            let src = URL.createObjectURL(file)
            $('#coverimg').prop('src',src)
        }

        //获取文章类别
        function getList() {
            $.ajax({
                url: '/admin/category/list',
                success(res) {
                    // console.log(res)
                    let data = res.data
                    let html = `<option value="">全部分类</option>`
                    data.forEach(item => {
                        html += `<option value=${item.id}>${item.name}</option>`
                    });
                    $('#category').html(html)
                }
                })
            }
        getList()
        
        //日期功能
        function getDate() {
            var laydate = layui.laydate;

            //执行一个laydate实例
            laydate.render({
            elem: '#articleDate' //指定元素
            });
        }
        getDate()

        //富文本框功能
        tinymce.init({
        selector: '#articleContent',
        language:'zh_CN'
         });
        }
        
        
    init()

    //点击发布获取表单的值
    $('.btn-edit').click(function () {
        savaArticle('已发布')
        
    })
    
    //点击存入草稿获取表单的值
    $('.btn-draft').click(function () {
        savaArticle('')
    })

    //封装保存和存入草稿的函数
    function savaArticle(state) {
        
        let formData = new FormData($('.article_form')[0])
        formData.append('content', tinyMCE.editors['articleContent'].getContent())
        formData.append('state',state)
        formData.forEach((key, value) => {
            console.log(value,key)
        })
        $.ajax({
            url: '/admin/article/publish',
            type: 'post',
            data: formData,
            contentType:false,
            processData: false,
            success(res) {
                console.log(res)
                // $('#inputTitle').val('')
                // $('#category').val('')
                // $('#articleDate').val("")
                // tinyMCE.editors['articleContent'].setContent('')
                layer.msg(res.msg)
                setTimeout(() => {
                    location.href = 'article_list.html'
                }, 1500);

            }
        })
    }
})